# -*- coding: utf-8 -*-
"""
模板注册表，实现与前端一致的模块化定义。
"""
from __future__ import annotations

from typing import Dict, List, Optional

from app.blueprints.reports.providers.starrocks.cps_quality import (
    CPSDataQualityProvider,
)
from app.blueprints.reports.providers.starrocks.generic_data_quality import (
    GenericDataQualityProvider,
)
from app.blueprints.reports.providers.starrocks.cps_base_statistics import (
    CPSBaseStatisticsProvider,
)

from .descriptor import TemplateDescriptor


class TemplateRegistry:
    _templates: Dict[str, TemplateDescriptor] = {}

    @classmethod
    def register(cls, descriptor: TemplateDescriptor) -> None:
        cls._templates[descriptor.code] = descriptor

    @classmethod
    def get(cls, code: Optional[str]) -> Optional[TemplateDescriptor]:
        if not code:
            return None
        return cls._templates.get(code)

    @classmethod
    def list(cls) -> List[TemplateDescriptor]:
        return list(cls._templates.values())


# ---- 预置模板，与前端 registry 对齐 ----
cps_default_params = {
    "data_source_config": {"data_source_id": None},
    "platform_selection": {
        "selected_platforms": ["dy"],
        "include_summary": True,
    },
    "time_filter": {
        "time_range_type": "all",
        "time_start": None,
        "time_end": None,
    },
    "threshold_config": {"sync_rate_threshold": 80},
    "display_fields": [
        "platform_summary",
        "platform",
        "source_total_count",
        "dws_total_count",
        "dws_on_sale_count",
        "dws_off_sale_count",
        "sync_rate",
        "data_status",
    ],
    "field_labels": {},
    "use_chinese_platform_name": True,
}

TemplateRegistry.register(
    TemplateDescriptor(
        code="cps_data_quality_monitor",
        name="CPS 数据质量监控报表",
        group="starrocks",
        description="支持多平台选择与时间筛选的 CPS 监控报表",
        provider_class=CPSDataQualityProvider,
        default_params=cps_default_params,
        output_formats=["html", "excel"],
        display_fields=cps_default_params["display_fields"],
    )
)

generic_data_quality_default_params = {
    "source_tables": {
        "data_source_id": None,
        "database_name": "",
        "table_names": [],
        "tables": [
            {
                "table_name": "",
                "distinct_field": "id",
                "time_field": "etl_date",
                "use_distinct": True,
            }
        ],
        "time_range_type": "all",
        "time_start": None,
        "time_end": None,
    },
    "target_table_config": {
        "data_source_id": None,
        "database_name": "",
        "table_name": "",
        "join_field": "id",
        "time_field": "etl_date",
        "filter_conditions": [],
        "stat_fields": {},
    },
    "filter_rules": {
        "sync_rate_threshold": 80,
    },
    "display_fields": [
        "source_total_count",
        "target_total_count",
        "sync_rate",
        "data_status",
    ],
    "field_labels": {
        "source_total_count": "源表总数",
        "target_total_count": "目标表总数",
        "sync_rate": "同步率",
        "data_status": "数据状态",
    },
    "stat_field_mappings": {},
}

TemplateRegistry.register(
    TemplateDescriptor(
        code="generic_data_quality_monitor",
        name="通用数据质量监控报表",
        group="starrocks",
        description="通用数据质量监控报表，支持多源表、单目标表、可选筛选条件、可选统计字段，适用于各种业务场景",
        provider_class=GenericDataQualityProvider,
        default_params=generic_data_quality_default_params,
        output_formats=["html", "excel"],
        display_fields=generic_data_quality_default_params["display_fields"],
    )
)

cps_base_statistics_default_params = {
    "data_source_config": {"data_source_id": None},
    "platform_filter": {
        "selected_platforms": ["dy", "tb", "jd", "pdd"],
    },
    "time_comparison": {
        "comparison_type": "day",
        "base_date": None,
        "compare_date": None,
    },
    "display_fields": [
        "data_comment",
        "platform",
        "base_date_count",
        "compare_date_count",
        "increment",
        "growth_rate",
        "trend",
    ],
}

TemplateRegistry.register(
    TemplateDescriptor(
        code="cps_base_statistics_report",
        name="CPS基础表统计报表",
        group="starrocks",
        description="统计各平台在两个时间点的商品增量情况，支持天/月/年对比。通过对比基准日期和对比日期的商品总数，计算增量、环比增长率等关键指标",
        provider_class=CPSBaseStatisticsProvider,
        default_params=cps_base_statistics_default_params,
        output_formats=["html", "excel"],
        display_fields=cps_base_statistics_default_params["display_fields"],
    )
)

# ---- 新增报表模板 ----

# 1. StarRocks集群对比报表
from app.blueprints.reports.providers.starrocks.cluster_comparison import (
    ClusterComparisonProvider,
)

cluster_comparison_default_params = {
    "source_cluster_config": {"data_source_id": None},
    "target_cluster_config": {"data_source_id": None},
    "table_selection": {
        "selection_type": "specific_tables",
        "database_name": "",
        "table_names": []
    },
    "display_fields": [
        "table_name",
        "source_rows",
        "source_size",
        "target_rows",
        "target_size",
        "row_diff",
        "size_diff",
        "diff_rate"
    ]
}

TemplateRegistry.register(
    TemplateDescriptor(
        code="starrocks_cluster_comparison_report",
        name="StarRocks集群对比报表",
        group="starrocks",
        description="对比两个StarRocks集群相同表的数据量，支持行数、数据大小对比",
        provider_class=ClusterComparisonProvider,
        default_params=cluster_comparison_default_params,
        output_formats=["html", "excel"],
        display_fields=cluster_comparison_default_params["display_fields"],
    )
)

# 2. Kafka Topic无新增监控报表
from app.blueprints.reports.providers.kafka.topic_no_update import (
    TopicNoUpdateProvider,
)

topic_no_update_default_params = {
    "kafka_cluster_config": {"cluster_id": None},
    "topic_selection": {"topic_names": []},
    "time_thresholds": {
        "thresholds": ["1_day"],
        "sort_by_staleness": True
    },
    "display_fields": [
        "topic_name",
        "partition_id",
        "last_message_time",
        "hours_no_update",
        "status"
    ]
}

TemplateRegistry.register(
    TemplateDescriptor(
        code="kafka_topic_no_update_report",
        name="Kafka Topic无新增监控报表",
        group="kafka",
        description="监控Kafka Topic的新增情况，检测哪些Topic在指定时间内没有新的消息",
        provider_class=TopicNoUpdateProvider,
        default_params=topic_no_update_default_params,
        output_formats=["html", "excel"],
        display_fields=topic_no_update_default_params["display_fields"],
    )
)

# 3. StarRocks表数据增长统计报表
from app.blueprints.reports.providers.starrocks.table_growth import (
    TableGrowthProvider,
)

table_growth_default_params = {
    "starrocks_cluster_config": {"cluster_id": None},
    "table_selection": {
        "selection_type": "specific_tables",
        "database_names": [],
        "table_names": []
    },
    "statistics_config": {
        "stat_type": "full_report",
        "top_n": 10,
        "sort_by": "row_increment"
    },
    "time_dimension": {
        "dimension_type": "last_day"
    },
    "display_fields": [
        "database",
        "table",
        "current_rows",
        "current_size",
        "row_increment",
        "size_increment",
        "growth_status"
    ]
}

TemplateRegistry.register(
    TemplateDescriptor(
        code="starrocks_table_growth_report",
        name="StarRocks表数据增长统计报表",
        group="starrocks",
        description="统计StarRocks表的数据增长情况，支持无新增表筛选、增量TOP排序、全量报表",
        provider_class=TableGrowthProvider,
        default_params=table_growth_default_params,
        output_formats=["html", "excel"],
        display_fields=table_growth_default_params["display_fields"],
    )
)


